package cn.monkey.family.server.domain.shop.item.type;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.context.Context;
import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.shop.item.type.ItemTypeDto;
import cn.monkey.family.data.shop.item.type.ItemTypeQueryRequest;
import cn.monkey.family.data.shop.item.type.ItemTypeVo;
import com.google.common.base.Strings;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("shop/item-type")
public class ItemTypeController {

    private final IItemTypeService itemTypeService;

    public ItemTypeController(IItemTypeService itemTypeService) {
        this.itemTypeService = itemTypeService;
    }

    @GetMapping({"{id}", ""})
    public Result<?> get(@Context RequestContext requestContext,
                         @PathVariable(value = "id", required = false) String id,
                         @RequestParam(value = "action", required = false) String action,
                         @RequestParam(value = "maxDeep", required = false) Integer maxDeep,
                         ItemTypeQueryRequest queryRequest,
                         @PageableDefault Pageable pageable) {
        if (!Strings.isNullOrEmpty(id)) {
            return this.itemTypeService.readById(requestContext, id);
        }
        if ("tree".equals(action)) {
            return this.itemTypeService.readTree(queryRequest, pageable.getSort(), maxDeep);
        }
        if ("distinctKey".equals(action)) {
            return this.itemTypeService.distinctKey(queryRequest, pageable.getSort());
        }
        return this.itemTypeService.readPage(requestContext, queryRequest, pageable);
    }

    @PostMapping
    public Result<ItemTypeVo> add(@Context RequestContext requestContext,
                                  @RequestBody ItemTypeDto item) {
        return this.itemTypeService.create(requestContext, item);
    }

    @DeleteMapping("{id}")
    public Result<Void> delete(@Context RequestContext requestContext,
                               @PathVariable("id") String id) {
        return this.itemTypeService.delete(requestContext, id);
    }

}
